package cn.jsu.oj.judgment.utils;

import io.netty.channel.Channel;

import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * net工具
 *
 * @author shan
 * @date 2022/06/30
 */
public class NetUtil {

    /**
     * 获取ip、port
     *
     * @param channel 通道
     * @return {@link Object[] }
     */
    public static Object[] getIpAndPort(Channel channel) {
        Object[] objects = new Object[2];
        InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
        objects[0] = inetSocketAddress.getAddress().getHostAddress();
        objects[1] = inetSocketAddress.getPort();
        return objects;
    }

    /**
     * 获取ip
     *
     * @param channel 通道
     * @return {@link String }
     */
    public static String getIp(Channel channel) {
        Object[] objects = getIpAndPort(channel);
        return objects[0].toString();
    }

    /**
     * 获取消息源
     *
     * @param channel 通道
     * @return {@link String }
     */
    public static String getIdentify(Channel channel) {
        Object[] ipAndPort = NetUtil.getIpAndPort(channel);
        return ipAndPort[0] + "-" + ipAndPort[1];
    }

    public static String getHostAddress() {
        try {
            return Inet4Address.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }
}
